import 'dart:math';
import 'package:flutter_common_ui/src/common_ui_config.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_smart_dialog/src/kit/view_utils.dart';

final _loadTags = <String>[];

///是否已经存在显示的loading
bool isLoadingExist() {
  _loadTags.removeWhere((it) => !SmartDialog.checkExist(tag: it));
  return _loadTags.isNotEmpty;
}

///显示 loading
LoadingController showLoadingDialog({
  String? tag,
  String? msg,
  int? value,
  bool clickMaskDismiss = false,
  bool? backDismiss,
}) {
  final controller = LoadingController(initTag: tag, initMsg: msg, initValue: value); // 绑定唯一tag
  SmartDialog.show(
    tag: controller.tag,
    useAnimation: false,
    backType: backDismiss == null ? null : (backDismiss == true ? SmartBackType.normal : SmartBackType.block),
    builder: (ctx) => Obx(() => LoadingWidget(msg: controller.message.value, value: controller.value.value)),
    onDismiss: () {
      _loadTags.remove(controller.tag);
    },
    maskColor: const Color.fromRGBO(0, 0, 0, 0.1),
    clickMaskDismiss: clickMaskDismiss,
  );
  _loadTags.add(controller.tag);
  return controller;
}

//隐藏 loading
Future hideLoadingDialog([String? tag]) {
  _loadTags.remove(tag);
  return SmartDialog.dismiss(tag: tag ?? _loadTags.lastOrNull);
}

//是否存在 loading
bool checkExist([String? tag]) {
  return SmartDialog.checkExist(tag: tag ?? _loadTags.lastOrNull);
}

// 创建状态管理类
class LoadingController {
  final String tag;

  // 响应式消息
  final RxString message;

  // 响应式 值
  final RxnInt value;

  LoadingController({String? initTag, String? initMsg, int? initValue})
      : tag = initTag ?? (1000000 + Random().nextInt(999999)).toString(),
        message = RxString(initMsg ?? CommonUiConfig.i18KeyLoading.tr),
        value = RxnInt(initValue);

  void updateMessage(String? msg) {
    message.value = msg ?? CommonUiConfig.i18KeyLoading.tr;
  }

  void updateValue(int? v) {
    value.value = v;
  }

  bool isExist() {
    return checkExist(tag);
  }

  void dismiss() {
    hideLoadingDialog(tag);
  }
}

/// 自定义Loading框
class LoadingWidget extends StatelessWidget {
  const LoadingWidget({super.key, required this.msg, this.value});

  ///loading msg
  final String msg;

  ///loading value
  final int? value;

  @override
  Widget build(BuildContext context) {
    final progress = value;
    final contentWidget = progress == null
        ? CircularProgressIndicator(
            strokeWidth: 3,
            valueColor: AlwaysStoppedAnimation(ThemeStyle.textColor),
          )
        : Stack(
            children: [
              SizedBox(
                width: 50,
                height: 50,
                child: CircularProgressIndicator(
                  value: progress / 100,
                  backgroundColor: Colors.grey.shade300,
                  strokeWidth: 3,
                  color: Theme.of(context).primaryColor,
                ),
              ),
              //进度
              Positioned.fill(
                child: Center(
                  child: Text(
                    "$progress%",
                    style: TextStyle(color: ThemeStyle.textColor, fontSize: 14),
                  ),
                ),
              ),
            ],
          );
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
      decoration: BoxDecoration(
        color: ThemeStyle.backgroundColor,
        borderRadius: BorderRadius.circular(15),
      ),
      child: Column(mainAxisSize: MainAxisSize.min, children: [
        //loading animation
        contentWidget,
        //msg
        Container(
          margin: const EdgeInsets.only(top: 15),
          child: Text(msg, style: TextStyle(color: ThemeStyle.textColor)),
        ),
      ]),
    );
  }
}

class LoadingDialog {
  static Widget dialog({
    String msg = 'loading...',
  }) {
    return Container(
      width: 120,
      height: 120,
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            width: 46,
            height: 46,
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation(CommonUiConfig.getLoadAndRetryCircleColor()),
              strokeWidth: 2,
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          Offstage(
            offstage: false,
            child: Text(
              msg,
              style: TextStyle(color: CommonUiConfig.getLoadAndRetryCircleColor(), fontSize: 12),
            ),
          )
        ],
      ),
    );
  }
}
